/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.behavior;

import com.eelpo.cmmp.core.wicket.component.label.FeedbackLabel;
import com.eelpo.common.util.BlankUtils;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.Model;

/**
 * <pre>
 * 
 * 组件出现错误的样式策略
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class ComponentVisualErrorBehavior extends AjaxFormComponentUpdatingBehavior {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -4607665719509594687L;

	protected FeedbackLabel feedbackLabel;

	public ComponentVisualErrorBehavior() {
		super("onblur");
	}

	public ComponentVisualErrorBehavior(String event) {
		super(event);
	}

	public ComponentVisualErrorBehavior(FeedbackLabel feedbackLabel) {
		super("onblur");
		this.feedbackLabel = feedbackLabel;
	}

	public ComponentVisualErrorBehavior(String event, FeedbackLabel feedbackLabel) {
		super(event);
		this.feedbackLabel = feedbackLabel;
	}

	@Override
	protected void onError(AjaxRequestTarget target, RuntimeException e) {
		changeCssClass(target, false, "invalid");
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior#onUpdate
	 * (org.apache.wicket.ajax.AjaxRequestTarget)
	 */
	@Override
	protected void onUpdate(AjaxRequestTarget target) {
		changeCssClass(target, true, "valid");
	}

	protected void changeCssClass(AjaxRequestTarget target, boolean valid, String cssClass) {

		FormComponent<?> formComponent = getFormComponent();

		if (BlankUtils.isBlank(feedbackLabel)) {
			if (formComponent.isValid() == valid) {
				formComponent.add(new AttributeModifier("class", true, new Model<String>("formcomponent " + cssClass)));
				target.addComponent(formComponent);
			}
		} else {

			feedbackLabel.valid();

			if (feedbackLabel.isChanged()) {

				if (formComponent.isValid() == valid) {
					formComponent.add(new AttributeModifier("class", true, new Model<String>("formcomponent " + cssClass)));
					target.addComponent(formComponent);
				}

				if (!BlankUtils.isBlank(feedbackLabel)) {
					target.addComponent(feedbackLabel);
				}
			}
		}
	}
}
